#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Ahem...

# pyid3tabs - a tab grabber for your id3
# Copyright (C) 2008 - Matheus P. Andrade
# based on original idea by Fabio K. Ramos
# with elegance and style added by Sabrina Leandro 
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


try:
	from mutagen.easyid3 import EasyID3
	from mutagen.id3 import ID3, USLT, ID3NoHeaderError
except ImportError:
	print "ERROR: This script requires the Mutagen module: <http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen>"
	sys.exit(1) 	

import sys
import commands
import re
import os
import glob

from fetchtabs import Tab

## From the 3rd example in http://www.pythonbrasil.com.br/moin.cgi/TiradorDeAcentos
def asciize(s):

	_table = {
		"á" : "a", "à" : "a", "â" : "a", "ä" : "a", "ã" : "a", "å" : "a",
		"é" : "e", "è" : "e", "ê" : "e", "ë" : "e",
		"í" : "i", "ì" : "i", "î" : "i", "ï" : "i",
		"ó" : "o", "ò" : "o", "ô" : "o", "ö" : "o", "õ" : "o", "ø" : "o",
		"ú" : "u", "ù" : "u", "û" : "u", "ü" : "u",
		"ñ" : "n", "ç" : "c",
		"Á" : "A", "À" : "A", "Â" : "A", "Ä" : "A", "Ã" : "A", "Å" : "A",
		"É" : "E", "È" : "E", "Ê" : "E", "Ë" : "E",
		"Í" : "I", "Ì" : "I", "Î" : "I", "Ï" : "I",
		"Ó" : "O", "Ò" : "O", "Ô" : "O", "Ö" : "O", "Õ" : "O", "Ø" : "O",
		"Ú" : "U", "Ù" : "U", "Û" : "U", "Ü" : "U",
		"Ñ" : "N", "Ç" : "C",
		"ß" : "ss", "Þ" : "d" , "æ" : "ae",
	# Added by me
		"'" : "", "'" : "", "`" : "", "(" : "" , ")" : "",
		'"' : "", "&" : "and"
	}

	for original, plain in _table.items():
	    s = s.replace(unicode(original, 'utf-8'), unicode(plain, 'utf-8'))
	return s

def locate_files(pattern, folder=None):
	"""Returns files on folder matching pattern	
	"""
	if not folder:
		folder = os.curdir
	pattern = os.path.join(folder, pattern)
	filenames = glob.glob(pattern)
	return filenames

def main():
	"""Usage: python pyid3tabs.py <filename|\"glob\" pattern>"""
	try:
		pattern = sys.argv[1]
	except:
		print main.__doc__
		return 1
	
	filenames = locate_files(pattern)
	for filename in filenames:
		try:
			audio = EasyID3(filename)
			audio_id3 = ID3(filename)
		except (IOError, ID3NoHeaderError), e:
			print "ERROR: Problem opening file %s: %s\n" % (filename, e)
			continue		
		
		artist_id3 = audio.get("artist", None)
		title_id3 = audio.get("title", None)
		if not artist_id3  or not title_id3:
			print "ERROR: Not enough information for file %s\n" % (filename)
			continue
			
		artist = asciize(artist_id3[0].lower())
		title = asciize(title_id3[0].lower())
		
		tab = Tab()
		id3tab = tab.search_tab(artist, title)
		if id3tab:
			tabname = artist + "-" + title + ".tab"
			tabfile = open(tabname, "w")
			tabfile.write(id3tab)
			tabfile.close()
			
			comment = 'http://code.google.com/p/pyid3tabs'
			lang_tab = u'eng'
			#audio_id3["USLT::'eng'"] = ""
			audio_id3.add(USLT(encoding=3, desc=comment, lang=lang_tab, text=id3tab))
			print "SAVED: \"%s - %s\" in file \"%s\"\n" % (artist_id3[0], title_id3[0], filename)
			
		else:
			print "NOT FOUND: \"%s - %s\" in file \"%s\"\n" % (artist_id3[0], title_id3[0], filename)

	return 0

if __name__ == '__main__':
	print "Ola!\n"
	status = main()
	print "Adeus..."
	sys.exit(status)